package com.bsoft.gol.hbs.service.impl;

import com.bsoft.gol.hbs.bean.qo.IniitAllConfigQo;
import com.bsoft.gol.hbs.service.SystemInitService;
import com.bsoft.gol.hbs.utils.CommonUtils;
import ctd.controller.exception.ControllerException;
import ctd.dictionary.Dictionary;
import ctd.dictionary.DictionaryItem;
import ctd.dictionary.controller.DictionaryController;
import ctd.net.rpc.Client;
import ctd.net.rpc.util.ServiceAdapter;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import ctd.util.context.ContextUtils;
import hcn.base.Product;
import hcn.base.StandardDept;
import hcn.service.base.qo.QueryStandardDeptListByParamsQo;
import org.atag.init.impl.LocalDictionaryInitialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import service.rpc.BaseStandardDeptIntf;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 租户参数初始化，包含字典
 * Created by ChenJij on 2021/12/27.
 */
@SsdevService("systemInitService")
public class SystemInitServiceImpl implements SystemInitService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SystemInitServiceImpl.class);

    @Autowired
    private BaseStandardDeptIntf baseStandardDeptService;
    @Autowired
    private LocalDictionaryInitialization localDictionaryInitialization;


    @RpcService
    public void initAllDicFromFile(String tenantId){

        Map<String, Object> initParams = new HashMap<>();
        initParams.put("tenantId", tenantId);
        List<String> packageToScan = Arrays.asList("hcn.base.dictionary", "hcn.health.dictionary", "hcn.mpi.dictionary",
                "hcn.ods.dictionary", "hcn.phr.dictionary", "pcn.core.dictionary");
        initParams.put("packageToScan", packageToScan);

        localDictionaryInitialization.init(initParams);
    }

    /**
     * @description: 初始化所有字典
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/12/23 15:08
     * @param:
     * @return: void
     */
    @RpcService
    public void initAllDic(){
        LOGGER.info("初始化所有字典开始");
        insertDic("hcn.base.dictionary.areaLevel");
        insertDic("hcn.base.dictionary.baseModule");
        insertDic("hcn.base.dictionary.bedType");
        insertDic("hcn.base.dictionary.bl_copycontent");
        insertDic("hcn.base.dictionary.bl_use");
        insertDic("hcn.base.dictionary.blType");
        insertDic("hcn.base.dictionary.CC04_30_018");
        insertDic("CV04_50_020");
        insertDic("hcn.base.dictionary.CC54_01_001_03");
        insertDic("hcn.base.dictionary.CC54_10_001_01");
        insertDic("hcn.base.dictionary.CC63_01_001_32");
        insertDic("hcn.base.dictionary.copywriter");
        insertDic("CV02_01_101");
        insertDic("CV04_50_005");
        insertDic("CV07_10_003");
        insertDic("hcn.base.dictionary.CV08_50_002");
        insertDic("hcn.base.dictionary.CVX_CardType");
        insertDic("hcn.base.dictionary.CVX_OrdersIdentification");
        insertDic("hcn.base.dictionary.delivery");
        insertDic("hcn.base.dictionary.deptGrade");
        insertDic("hcn.base.dictionary.digitalWardFuncTypes");
        insertDic("hcn.base.dictionary.doctorTitle");
        insertDic("hcn.base.dictionary.expertFlag");
        insertDic("hcn.base.dictionary.feedback");
        insertDic("hcn.base.dictionary.GB_T2261_1");
        insertDic("hcn.base.dictionary.GB_T2261_2");
        insertDic("hcn.base.dictionary.GB_T3304");
        insertDic("hcn.base.dictionary.GB_T4658");
        insertDic("hcn.base.dictionary.GB_T4761");
        insertDic("hcn.base.dictionary.gender");
        insertDic("hcn.base.dictionary.HCN_adviceType");
        insertDic("hcn.base.dictionary.HCN_antibiosisType");
        insertDic("hcn.base.dictionary.HCN_antibioticLevel");
        insertDic("hcn.base.dictionary.HCN_appealType");
        insertDic("hcn.base.dictionary.HCN_appealVerifyState");
        insertDic("hcn.base.dictionary.HCN_areaRoomType");
        insertDic("hcn.base.dictionary.HCN_askLeaveType");
        insertDic("hcn.base.dictionary.HCN_bannerPostion");
        insertDic("hcn.base.dictionary.HCN_baseDataSource");
        insertDic("hcn.base.dictionary.HCN_baseDataType");
        insertDic("hcn.base.dictionary.HCN_csrItem");
        insertDic("hcn.base.dictionary.HCN_csrRank");
        insertDic("hcn.base.dictionary.HCN_csrType");
        insertDic("hcn.base.dictionary.HCN_departmentOtherType");
        insertDic("hcn.base.dictionary.HCN_departmentType");
        insertDic("hcn.base.dictionary.HCN_deptAuthority");
        insertDic("hcn.base.dictionary.HCN_diseaseForCrowd");
        insertDic("hcn.base.dictionary.HCN_doctorTitle");
        insertDic("hcn.base.dictionary.HCN_feedback");
        insertDic("hcn.base.dictionary.HCN_feedbackClassify");
        insertDic("hcn.base.dictionary.HCN_feeDocumentType");
        insertDic("hcn.base.dictionary.HCN_feeType");
        insertDic("hcn.base.dictionary.HCN_guideType");
        insertDic("hcn.base.dictionary.HCN_houseHold");
        insertDic("hcn.base.dictionary.HCN_hyperLink");
        insertDic("hcn.base.dictionary.HCN_inpatientType");
        insertDic("hcn.base.dictionary.HCN_inspectionReportType");
        insertDic("hcn.base.dictionary.HCN_leaveStatus");
        insertDic("hcn.base.dictionary.HCN_matchParams");
        insertDic("hcn.base.dictionary.HCN_matchType");
        insertDic("WS218");
        insertDic("hcn.base.dictionary.HCN_medicalCombType");
        insertDic("hcn.base.dictionary.HCN_monitoringItem");
        insertDic("hcn.base.dictionary.HCN_monitoringType");
        insertDic("hcn.base.dictionary.HCN_nationality");
        insertDic("hcn.base.dictionary.HCN_networkType");
        insertDic("hcn.base.dictionary.HCN_objectType");
        insertDic("hcn.base.dictionary.HCN_operator");
        insertDic("sys.org.orgtp");
        insertDic("hcn.base.dictionary.HCN_organizationType");
        insertDic("hcn.base.dictionary.HCN_outpatientSchedulingService");
        insertDic("hcn.base.dictionary.HCN_outpatientSourceType");
        insertDic("hcn.base.dictionary.HCN_payMethod");
        insertDic("hcn.base.dictionary.HCN_practiceCategory");
        insertDic("hcn.base.dictionary.HCN_readMark");
        insertDic("hcn.base.dictionary.HCN_refundApplyType");
        insertDic("hcn.base.dictionary.HCN_refundReason");
        insertDic("hcn.base.dictionary.HCN_refundStatus");
        insertDic("hcn.base.dictionary.HCN_registrationStatus");
        insertDic("hcn.base.dictionary.HCN_regType");
        insertDic("hcn.base.dictionary.HCN_reportSource");
        insertDic("hcn.base.dictionary.HCN_reportType");
        insertDic("hcn.base.dictionary.HCN_reservationApproach");
        insertDic("hcn.base.dictionary.HCN_svrItemCode");
        insertDic("hcn.base.dictionary.HCN_svrItemType");
        insertDic("hcn.base.dictionary.HCN_svrOpenProperty");
        insertDic("hcn.base.dictionary.HCN_svrPayType");
        insertDic("hcn.base.dictionary.HCN_svrPriceModel");
        insertDic("hcn.base.dictionary.HCN_svrPriceUnit");
        insertDic("hcn.base.dictionary.HCN_svrRegDataSource");
        insertDic("hcn.base.dictionary.HCN_svrRuleType");
        insertDic("hcn.base.dictionary.HCN_svrTalkType");
        insertDic("hcn.base.dictionary.HCN_tradeStatus");
        insertDic("hcn.base.dictionary.HCN_tradeType");
        insertDic("hcn.base.dictionary.HCN_treatmentType");
        insertDic("hcn.base.dictionary.HCN_verifyDescType");
        insertDic("hcn.base.dictionary.HCN_verifyState");
        insertDic("hcn.base.dictionary.HCN_yesAndNoType");
        insertDic("hcn.base.dictionary.medicalCombType");
        insertDic("hcn.base.dictionary.msgNoticeType");
        insertDic("hcn.base.dictionary.networkType");
        insertDic("hcn.base.dictionary.objectType");
        insertDic("hcn.base.dictionary.operator");
        insertDic("sys.org.orgtp");
        insertDic("hcn.base.dictionary.organizationType");
        insertDic("WS218");
        insertDic("hcn.base.dictionary.practiceCategory");
        insertDic("hcn.base.dictionary.product");
        insertDic("hcn.base.dictionary.relation");
        insertDic("hcn.base.dictionary.status");
        insertDic("hcn.base.dictionary.zxFlag");
        insertDic("CV03_00_302");
        insertDic("hcn.health.dictionary.education");
        insertDic("CV03_00_303");
        insertDic("CV02_01_204");
        insertDic("hcn.health.dictionary.livestockColumn");
        insertDic("hcn.health.dictionary.personGroup");
        insertDic("hcn.health.dictionary.registeredPermanent");
        insertDic("CV03_00_304");
        insertDic("CV03_00_115");
        insertDic("hcn.health.dictionary.workCode");
        insertDic("CV04_50_005");
        insertDic("hcn.mpi.dictionary.cardType");
        insertDic("CV02_01_101");
        insertDic("hcn.mpi.dictionary.education");
        insertDic("hcn.mpi.dictionary.GB_T2261_4");
        insertDic("CV03_00_107");
        insertDic("CV03_00_104");
        insertDic("CV03_00_111");
        insertDic("CV03_00_101");
        insertDic("hcn.mpi.dictionary.houseHold");
        insertDic("CV02_01_204");
        insertDic("hcn.mpi.dictionary.maritalStatus");
        insertDic("hcn.mpi.dictionary.nation");
        insertDic("hcn.mpi.dictionary.nationality");
        insertDic("CV04_50_020");
        insertDic("hcn.mpi.dictionary.uniqueIdSource");
        insertDic("hcn.mpi.dictionary.uniqueIdType");
        insertDic("hcn.ods.dictionary.advicePeriod");
        insertDic("hcn.ods.dictionary.adviceType");
        insertDic("hcn.ods.dictionary.antibiosisType");
        insertDic("hcn.ods.dictionary.antibioticLevel");
        insertDic("hcn.ods.dictionary.askLeaveType");
        insertDic("hcn.ods.dictionary.bedRestrictFlag");
        insertDic("hcn.ods.dictionary.bedStatus");
        insertDic("hcn.ods.dictionary.deptAuthority");
        insertDic("hcn.ods.dictionary.diseaseForCrowd");
        insertDic("CV08_50_002");
        insertDic("hcn.ods.dictionary.examReportType");
        insertDic("hcn.ods.dictionary.inpatientType");
        insertDic("hcn.ods.dictionary.inpormtant");
        insertDic("hcn.ods.dictionary.insuranceLevel");
        insertDic("hcn.ods.dictionary.labReportType");
        insertDic("hcn.ods.dictionary.labReportViewType");
        insertDic("hcn.ods.dictionary.leaveStatus");
        insertDic("hcn.ods.dictionary.registrationStatus");
        insertDic("hcn.ods.dictionary.regType");
        insertDic("hcn.ods.dictionary.reportFlowStatus");
        insertDic("hcn.ods.dictionary.reportSource");
        insertDic("hcn.ods.dictionary.tradeStatus");
        insertDic("hcn.ods.dictionary.tradeType");
        insertDic("hcn.phr.dictionary.readMark");
        insertDic("hcn.phr.dictionary.reportType");
        insertDic("pcn.base.dictionary.doctorTitle");
        insertDic("pcn.core.dictionary.appdocCancelReason");
        insertDic("pcn.core.dictionary.apptStatus");
        insertDic("pcn.core.dictionary.baseTimeConfig");
        insertDic("pcn.core.dictionary.cardType");
        insertDic("pcn.core.dictionary.checkway");
        insertDic("pcn.core.dictionary.discountType");
        insertDic("pcn.core.dictionary.docType");
        insertDic("CV02_01_101");
        insertDic("pcn.core.dictionary.moduleGroup");
        insertDic("pcn.core.dictionary.nationality");
        insertDic("pcn.core.dictionary.personGroup");
        insertDic("pcn.core.dictionary.processType");
        insertDic("pcn.core.dictionary.programModuleCode");
        insertDic("pcn.core.dictionary.regWay");
        insertDic("pcn.core.dictionary.serviceFrequency");
        insertDic("pcn.core.dictionary.serviceSource");
        insertDic("pcn.core.dictionary.serviceWay");
        insertDic("pcn.core.dictionary.sexType");
        insertDic("pcn.core.dictionary.signCancelReason");
        insertDic("pcn.core.dictionary.signCycle");
        insertDic("pcn.core.dictionary.signPersonGroup");
        insertDic("pcn.core.dictionary.signSource");
        insertDic("pcn.core.dictionary.signStatus");
        insertDic("pcn.core.dictionary.suitableObject");
        insertDic("pcn.core.dictionary.timeUnit");
        insertDic("pcn.core.dictionary.unitType");
        insertDic("hcn.base.dictionary.measureMode");
        insertDic("hcn.base.dictionary.pathology");
        insertDic("hcn.base.dictionary.signCrucial");
        insertDic("hcn.base.dictionary.docTeamType");
        insertDic("hcn.base.dictionary.followType");
        LOGGER.info("初始化所有字典结束");
        //刷新缓存
        DictionaryController.instance().reloadAll();
    }


    /**
     * @description: 初始化对应路径的字典
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/12/23 16:53
     * @param: dicPath
     * @return: void
     */
    @RpcService
    public void insertDic(String dicPath){
        try {
            LOGGER.info("初始化对应路径的字典："+dicPath);
            Dictionary moduleDic = DictionaryController.instance().get(dicPath);
            List<DictionaryItem> dictionaryItems = moduleDic.getSlice(null, 0, null);
            //[{"id":"字典编码","cd":"字典编码","na":"字典名称","dicType":"1","ver":null,"dicLevel":"1","storageType":"1","public":"true","usageType":"2","usageDes":null,"des":"字典描述","modifyDate":null,"mnemonicCode":null,"py":null,"wb":null,"zj":null}]
            Map<String, Object> requestMap = new HashMap<>();
            //字典编码
            requestMap.put("id", moduleDic.getId());
            //字典编码
            requestMap.put("cd", moduleDic.getId());
            //字典名称
            requestMap.put("na", moduleDic.getName());
            //字典类型
            requestMap.put("dicType", "1");
            //字典等级
            requestMap.put("dicLevel", "1");
            //字典层级
            requestMap.put("storageType", "0");
            //是否公开
            requestMap.put("public", "true");
            //处理类型
            requestMap.put("usageType", "2");
            //字典描述
            requestMap.put("des", moduleDic.getName());
            //新增字典bl_use.dic
            ServiceAdapter.invokeWithJsonBytes("bbp.dicConfig", "createDic", requestMap);

            String tenantId = (String) ContextUtils.get("$tenantId");
            for (DictionaryItem dictionaryItem : dictionaryItems) {
                // 新增字典值
                ServiceAdapter.invoke("bbp.dicConfig", "createDictionaryItem", dicPath + "@" + tenantId,
                        dictionaryItem.getKey(), dictionaryItem.getText(), dictionaryItem.getParent());

            }
            //刷新缓存
            DictionaryController.instance().getUpdater().reload(dicPath + "@" + tenantId);
            LOGGER.info("初始化对应路径的字典结束："+dicPath);

        }catch (Exception e){
            e.printStackTrace();
            LOGGER.info("初始化对应路径的字典异常："+e.getMessage());

        }
    }

    /**
     * @description: 初始化标准科室
     * @author: chenJij@bsoft.com.cn
     * @param:
     * @return: void
     */
    @RpcService
    public void initStandardDeptDic(){
        QueryStandardDeptListByParamsQo qo = new QueryStandardDeptListByParamsQo();
        List<StandardDept> standardDepts = baseStandardDeptService.queryStandardDeptListByParamsQo(qo);
        if(CommonUtils.isNotEmpty(standardDepts)){
            for (StandardDept standardDept : standardDepts) {
                // 新增字典值
                try {
                    ServiceAdapter.invoke("bbp.dicConfig", "createDictionaryItem", "sys.org.hedomain",
                            standardDept.getStardardDeptCode(), standardDept.getStardardDeptName(), null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //刷新缓存
            try {
                DictionaryController.instance().getUpdater().reload("sys.org.hedomain");
            } catch (ControllerException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @description: 初始化产品
     * @author: chenJij@bsoft.com.cn
     * @param:
     * @return: void
     */
    @RpcService
    public void initProductDic(){
        try {
            List<Product> products = baseStandardDeptService.queryProductList();
            //[{"id":"字典编码","cd":"字典编码","na":"字典名称","dicType":"1","ver":null,"dicLevel":"1","storageType":"1","public":"true","usageType":"2","usageDes":null,"des":"字典描述","modifyDate":null,"mnemonicCode":null,"py":null,"wb":null,"zj":null}]
            Map<String, Object> requestMap = new HashMap<>();
            //字典编码
            requestMap.put("id", "hcn.base.dictionary.product");
            //字典编码
            requestMap.put("cd", "hcn.base.dictionary.product");
            //字典名称
            requestMap.put("na", "APP产品表");
            //字典类型
            requestMap.put("dicType", "1");
            //字典等级
            requestMap.put("dicLevel", "1");
            //字典层级
            requestMap.put("storageType", "0");
            //是否公开
            requestMap.put("public", "true");
            //处理类型
            requestMap.put("usageType", "2");
            //字典描述
            requestMap.put("des", "APP产品表");
            //新增字典bl_use.dic
            ServiceAdapter.invokeWithJsonBytes("bbp.dicConfig", "createDic", requestMap);

            String tenantId = (String) ContextUtils.get("$tenantId");
            for (Product product : products) {
                // 新增字典值
                ServiceAdapter.invoke("bbp.dicConfig", "createDictionaryItem", "hcn.base.dictionary.product" + "@" + tenantId,
                        product.getProductCode(), product.getProductName(), null);

            }
            //刷新缓存
            DictionaryController.instance().getUpdater().reload("hcn.base.dictionary.product" + "@" + tenantId);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * @description: 查询字典
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/10/27 13:27
     * @param: dicPath
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    @RpcService
    public Map<String,Object> queryDicFileCode(String dicPath) throws ControllerException {
        ctd.dictionary.Dictionary dictionary = DictionaryController.instance().get(dicPath);
        if(null != dictionary){
            List<DictionaryItem> dictionaryItems = dictionary.getSlice(null, 0, null);
            if(CommonUtils.isNotEmpty(dictionaryItems)){
                Map<String,Object> dictionaryMap = new HashMap<>();
                for (DictionaryItem dictionaryItem : dictionaryItems) {
                    dictionaryMap.put(dictionaryItem.getKey(),dictionaryItem.getText());
                }
                return dictionaryMap;
            }
        }
        return null;
    }


    /**
     * @description: 初始化所有配置
     * @author: chenJij@bsoft.com.cn
     * @date: 2022/12/8 14:53
     * @param: qo
     * @return: void
     */
    @RpcService
    public void initAllConfig(IniitAllConfigQo qo){
        //初始化各种机构配置和参数
        String finalOrgId = qo.getOrgId();
        //初始化参数配置
        try {
            Client.rpcInvoke("hbs.basePropertyConfig", "initBasePropertyConfig", finalOrgId);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        //初始化功能配置
        try {
            Client.rpcInvoke("hbs.baseLevelConfigService", "initBaseModuleConfig", finalOrgId);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        //初始化文案配置
        try {
            Client.rpcInvoke("hbs.baseCopywriterConfig", "initCopywriterConfig", finalOrgId);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        if(CommonUtils.isNotEmpty(finalOrgId)){
            //初始化排班设置
            try {
                Client.rpcInvoke("hco.schedulingService", "saveSchedulingSettings", finalOrgId);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        //初始化处方类型
        try {
            Client.rpcInvoke("cmc.commonPrescriptionService", "intPrescriptionTypeConfig",finalOrgId);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}